<template>
  <div class="category-list">
    <h2>分类 <span class="highlight">热卖</span></h2>
    <div class="category-item" @click="selectCategory('超级88大促')">
      <span>热销分类</span>
    </div>
    <div class="category-row" v-for="(chunk, index) in chunkedCategories" :key="index">
      <div v-for="category in chunk" :key="category.cId" class="category-item" @click="selectCategory(category.cName)">
        <span>{{ category.cName }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import goodApi from '@/api/controller'

export default {
  name: 'CategoryList',
  setup(props, { emit }) {
    const categories = ref([])

    const fetchCategories = async () => {
      try {
        const response = await goodApi.getCategoryListPage()
        categories.value = response.data.records || []
      } catch (error) {
        console.error('获取分类失败:', error)
      }
    }

    const selectCategory = (categoryName) => {
      emit('category-selected', categoryName)
    }

    onMounted(() => {
      fetchCategories()
    })

    const chunkedCategories = computed(() => {
      return categories.value.reduce((result, item, index) => {
        const chunkIndex = Math.floor(index / 3)
        if (!result[chunkIndex]) result[chunkIndex] = []
        result[chunkIndex].push(item)
        return result
      }, [])
    })

    return {
      categories,
      selectCategory,
      chunkedCategories
    }
  }
}
</script>

<style scoped>
.category-list {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 24px;
  margin: 20px;
  width: 350px;
}
.category-list h2 {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}
.category-list .highlight {
  color: #ff4d4f;
  font-weight: bold;
}
.category-row {
  display: flex;
  flex-wrap: wrap;
  margin: -5px;
}
.category-item {
  flex: 1 0 30%;
  box-sizing: border-box;
  padding: 5px;
}
.category-item > span {
  display: block;
  text-align: center;
  padding: 10px;
  border-radius: 4px;
  transition: background-color 0.3s, color 0.3s;
}
.category-item:hover > span {
  background-color: #e8f5e9;
  color: #ff4d4f;
}
.category-item > span {
  font-size: 14px;
  color: #333;
}
</style>